<template>
	<div class="ability-recommend-container text-df">
		<!--对话提示-->
		<chat-tip @askQuestion="handleAskQuestion"></chat-tip>
		<!--当前聊天对话-->
		<chat-chit ref="childRef" :chatHistory="chatHistory" :showChatTipTxt="showChatTipTxt" :showLoading="submitting"
			@resetScroll="resetScroll" @resetSubmit="resetSubmit" @askQuestion="handleAskQuestion"></chat-chit>
		<!-- 输入框部分 -->
		<div class="footer-section">
			<!-- 领域标签滚动区域 -->
			<div class="domain-scroll-container">
				<div class="domain-scroll-wrapper" ref="domainScrollRef" @touchstart="handleDomainTouchStart"
					@touchmove="handleDomainTouchMove" @touchend="handleDomainTouchEnd">
					<div v-for="(domain, index) in domainList" :key="index"
						:class="['domain-item', { 'active': activeDomain === domain }]"
						@click="handleDomainClick(domain)">
						<i :class="getDomainIcon(domain)"></i>
						<span>{{ domain }}</span>
					</div>
				</div>
				<!-- 滚动指示器 -->
				<div class="scroll-indicator" v-if="domainList.length > 3">
					<span v-for="(_, index) in Math.ceil(domainList.length / 3)" :key="index"
						:class="['indicator-dot', { 'active': currentDomainPage === index }]"></span>
				</div>
			</div>
			<div class="search-bar bg-white flex align-center padding-sm">
				<el-input v-model="inputTxt" placeholder="请输入问询的问题" @keyup.enter.native.prevent="submitInput"
					@keydown.enter.prevent>
				</el-input>
				<!--正在请求回答-->
				<template v-if="submitting">
					<div class="send-button interrupt-button" title="停止回答" @click="cancelRequest">
						<img src="../../assets/image/common/interrupt.png" />
					</div>
				</template>
				<!--提问-->
				<template v-else>
					<i class="aifont icon-fasong" @click="submitInput"></i>
				</template>

			</div>
		</div>
	</div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, reactive } from 'vue';
import Storage from '@/base/storage'
import chatTip from './components/chatTip.vue' // 对话提示（当前还没有对话过）
import chatChit from './components/chatChit.vue' //相关聊天对话
import { ElMessage } from "element-plus";
import { dateFormat } from "@/base/utils.js";
import axios from 'axios'; // 导入 axios
import { abilityData } from './components/abilityData.js'
import stringSimilarity from 'string-similarity'

const chatHistory = ref([])// 历史记录
const childRef = ref() // 聊天对话组件实例
let submitting = ref(false) // 正在回答中
let inputTxt = ref('') // 文本框绑定的值
const showChatTipTxt = ref('正在思考中...') // 提示文字
let ctrl = null // 流式对话对象
const recRef = ref(null) // 录音实例对象

// 存储取消时的输入内容
const canceledInput = ref('');

// 领域列表数据
const domainList = ref([
	'AI',
	'CT-网络',
	'服务能力',
	'管运',
	'核心能力',
	'基础能力',
	'区块链',
	'网运',
	'业务',
	'业运域'
]);

// 当前激活的领域
const activeDomain = ref('');

// 当前显示的页面索引
const currentDomainPage = ref(0);

// 领域触摸滑动相关状态
const domainScrollRef = ref(null);
const domainTouchState = reactive({
	startX: 0,
	currentX: 0,
	startScrollLeft: 0,
	isScrolling: false
});

// 添加新的状态变量
const retryCount = ref(0)
const maxRetries = 3

// 添加相似度匹配函数
const findMostSimilarAbility = (targetName) => {
	const names = abilityData.map(item => item.capability_name)
	const matches = stringSimilarity.findBestMatch(targetName, names)
	return matches.bestMatch.rating >= 0.6 ? abilityData[matches.bestMatchIndex] : null
}

// 获取领域对应的图标
const getDomainIcon = (domain) => {
	const iconMap = {
		'AI': 'iconfont guanli',
		'CT-网络': 'iconfont banli',
		'服务能力': 'iconfont weixiudan',
		'管运': 'iconfont guanli',
		'核心能力': 'iconfont banli',
		'基础能力': 'iconfont weixiudan',
		'区块链': 'iconfont guanli',
		'网运': 'iconfont banli',
		'业务': 'iconfont weixiudan',
		'业运域': 'iconfont guanli'
	};
	return iconMap[domain] || 'iconfont guanli';
};

// 处理领域触摸开始
const handleDomainTouchStart = (e) => {
	if (!domainScrollRef.value) return;

	const touch = e.touches[0];
	domainTouchState.startX = touch.clientX;
	domainTouchState.currentX = touch.clientX;
	domainTouchState.startScrollLeft = domainScrollRef.value.scrollLeft;
	domainTouchState.isScrolling = false;
};

// 处理领域触摸移动
const handleDomainTouchMove = (e) => {
	if (!domainScrollRef.value) return;

	const touch = e.touches[0];
	domainTouchState.currentX = touch.clientX;
	const deltaX = domainTouchState.currentX - domainTouchState.startX;

	// 判断是否是水平滑动
	if (!domainTouchState.isScrolling && Math.abs(deltaX) > 10) {
		domainTouchState.isScrolling = true;
	}

	if (domainTouchState.isScrolling) {
		// 阻止页面滚动
		e.preventDefault();

		// 计算新的scroll位置
		domainScrollRef.value.scrollLeft = domainTouchState.startScrollLeft - deltaX;

		// 更新当前页面索引
		updateDomainPageIndex();
	}
};

// 处理领域触摸结束
const handleDomainTouchEnd = () => {
	domainTouchState.isScrolling = false;
};

// 更新当前域页面索引
const updateDomainPageIndex = () => {
	if (!domainScrollRef.value) return;

	const scrollWidth = domainScrollRef.value.scrollWidth;
	const clientWidth = domainScrollRef.value.clientWidth;
	const scrollLeft = domainScrollRef.value.scrollLeft;

	const totalPages = Math.ceil(scrollWidth / clientWidth);
	const currentPage = Math.floor((scrollLeft / (scrollWidth - clientWidth)) * (totalPages - 1));

	currentDomainPage.value = Math.max(0, Math.min(currentPage, totalPages - 1));
};

// 取消请求
const cancelRequest = () => {
	if (submitting.value) {
		// 保存当前正在回答的问题
		const lastMessage = chatHistory.value[chatHistory.value.length - 1];
		if (lastMessage && lastMessage.msgType === '1') {
			canceledInput.value = lastMessage.content;
			// 移除最后一条用户消息
			chatHistory.value.pop();
		}

		// 取消请求
		if (ctrl) {
			ctrl.abort();
		}

		// 重置状态
		submitting.value = false;
		// 将取消的内容放回输入框
		inputTxt.value = canceledInput.value;
		canceledInput.value = '';
	}
}

// 修改提交按钮函数
const submitInput = async () => {
	if (submitting.value) {
		ElMessage({
			message: "请耐心等待助手完成回复后，才能继续提问哦",
			type: 'warning',
			plain: true,
		})
		return
	}

	if (inputTxt.value.trim()) {
		if (inputTxt.value.length > 500) {
			ElMessage({
				message: '超出输入上线，请删除部分内容后发送',
				type: 'warning',
				plain: true,
			})
			return
		}

		let key = inputTxt.value
		inputTxt.value = ''

		// 先设置加载状态
		submitting.value = true
		showChatTipTxt.value = '正在思考中...'

		// 添加用户消息
		chatHistory.value.push({
			id: new Date().getTime(),
			content: key,
			startTime: dateFormat(new Date(), 'MM-dd hh:mm'),
			msgType: '1'
		})

		resetScroll()

		try {
			await sendWorkflowRequest(key)
		} catch (error) {
			console.error('请求失败:', error)
			ElMessage({
				message: '网络请求失败，请稍后重试',
				type: 'error',
				plain: true,
			})
		} finally {
			submitting.value = false
			resetScroll()
		}
	} else {
		ElMessage({
			message: "发送内容不能为空",
			type: 'warning',
			plain: true,
		})
	}
}

// 滚动到底部
const resetScroll = () => {
	// 延迟一下，滚动底部，不然加载太慢了滚不到底部
	setTimeout(() => {
		let chatBox = document.querySelector('.ability-recommend-container')
		// 获取 chatBox 的父元素
		let parentBox = chatBox.parentElement;

		parentBox.scrollTo(0, parentBox.scrollHeight);
	}, 5)
}
const resetSubmit = () => {
	submitting.value = false;
	resetScroll()
}


// 修改请求工作流的函数
const sendWorkflowRequest = async (input) => {
	// 检查输入是否包含"领域"关键词
	const isDomainQuery = input.includes('领域');

	const token = 'pat_mh8TfwZeEWg4Ptv69j6yFnpwbDZ8hV4hiTfW2feEFWC9ZcK7jKzkI3v7f8glEadL';
	const url = 'https://api.coze.cn/v1/workflow/run';
	const headers = {
		'Authorization': `Bearer ${token}`,
		'Content-Type': 'application/json'
	};

	try {
		if (isDomainQuery) {
			// 使用领域相关的工作流
			const data = {
				"workflow_id": "7483037682177851432",
				"parameters": {
					"input": input
				},
				"is_async": false
			};

			const response = await axios.post(url, data, { headers });
			if (response && response.data) {
				const responseData = JSON.parse(response.data);
				if (responseData.code === 0 && responseData.data) {
					const outputData = JSON.parse(responseData.data).output;

					// 构建领域信息展示数据
					let item = {
						'id': new Date().getTime(),
						'startTime': dateFormat(new Date(), 'MM-dd hh:mm'),
						'msgType': '2',
						'domainInfo': {
							title: outputData.title,
							desc: outputData.desc,
							abilities: outputData.data
						}
					};
					chatHistory.value.push(item);
					// 确保传入有效的文本
					if (outputData.desc) {
						childRef.value.printText(outputData.desc);
					}
				}
			}
		} else {
			// 使用原有的工作流逻辑，但只获取能力名称
			const data = {
				"workflow_id": "7485192104815116324",
				"parameters": {
					"input": input,
					"type": "ability_query"
				},
				"is_async": false
			};

			const response = await axios.post(url, data, { headers });
			if (response && response.data) {
				const responseData = JSON.parse(response.data);
				if (responseData.code === 0 && responseData.data) {
					const outputData = JSON.parse(responseData.data);
					if (outputData && outputData.output && outputData.output.length > 0) {
						const capability_name = outputData.output[0].capability_name;

						// 在本地数据中查找完整信息
						let matchedAbility = abilityData.find(item => item.capability_name === capability_name);

						// 如果没有找到完全匹配，且重试次数未达到上限
						if (!matchedAbility && retryCount.value < maxRetries) {
							retryCount.value++;
							await sendWorkflowRequest(input);
							return;
						}

						// 如果重试后仍未找到完全匹配，尝试相似度匹配
						if (!matchedAbility && retryCount.value >= maxRetries) {
							matchedAbility = findMostSimilarAbility(capability_name);
						}

						// 重置重试计数
						retryCount.value = 0;

						if (matchedAbility) {
							// 构建能力卡片数据
							let item = {
								'id': new Date().getTime(),
								'startTime': dateFormat(new Date(), 'MM-dd hh:mm'),
								'msgType': '2',
								'content': '',
								'abilityInfoList': [{
									name: matchedAbility.capability_name,
									description: matchedAbility.capability_description,
									scenarios: matchedAbility.business_scenarios,
									firstCost: matchedAbility.initial_access_fee,
									yearCost: matchedAbility.unit_price,
									parentCapability: matchedAbility.parent_capability,
									tags: [
										matchedAbility.billing_type,
										matchedAbility.access_fee_required === '是' ? '首次接入计费' : '',
										`计费周期：${matchedAbility.billing_cycle}`
									].filter(Boolean)
								}]
							};
							chatHistory.value.push(item);
							// 确保传入有效的文本
							if (item.abilityInfoList[0].description) {
								childRef.value.printText(item.abilityInfoList[0].description);
							}
						} else {
							ElMessage({
								message: '未找到匹配的能力信息',
								type: 'warning',
								plain: true,
							});
						}
					}
				} else {
					throw new Error('服务响应异常');
				}
			}
		}
	} catch (error) {
		console.error('API请求失败:', error);
		ElMessage({
			message: '网络请求失败，请检查网络连接后重试',
			type: 'error',
			plain: true,
		});
	} finally {
		submitting.value = false;
		resetScroll();
	}
}

// 处理领域点击
const handleDomainClick = (domain) => {
	activeDomain.value = domain;
	const questions = {
		'AI': 'AI领域都包含哪些能力?',
		'CT-网络': 'CT-网络领域都包含哪些能力?',
		'服务能力': '服务能力领域都包含哪些能力?',
		'管运': '管运领域都包含哪些能力?',
		'核心能力': '核心能力领域都包含哪些能力?',
		'基础能力': '基础能力领域都包含哪些能力?',
		'区块链': '区块链领域都包含哪些能力?',
		'网运': '网运领域都包含哪些能力?',
		'业务': '业务领域都包含哪些能力?',
		'业运域': '业运域领域都包含哪些能力?'
	};

	inputTxt.value = questions[domain] || `${domain}领域都包含哪些能力?`;
	submitInput();
}

const handleAskQuestion = (question) => {
	inputTxt.value = question;
	submitInput();
}

onMounted(() => {
	// 从本地存储加载聊天历史
	chatHistory.value = Storage.get('chatHistory') || []

	// 监听滚动事件更新页面索引
	if (domainScrollRef.value) {
		domainScrollRef.value.addEventListener('scroll', updateDomainPageIndex);
	}
})
onUnmounted(() => {
	// 清除本地存储的聊天历史
	Storage.remove('chatHistory')

	// 移除滚动监听
	if (domainScrollRef.value) {
		domainScrollRef.value.removeEventListener('scroll', updateDomainPageIndex);
	}
})

</script>

<style scoped>
.ability-recommend-container {
	padding: 0 20px 160px 20px;
	background: #F3F6FC;
}

.footer-section {
	width: calc(100% - 40px);
	padding: 10px 0 22px 0;
	background: #F3F6FC;
	position: fixed;
	bottom: 0;
	z-index: 99;

	/* 领域滚动区域样式 */
	.domain-scroll-container {
		width: 100%;
		margin-bottom: 10px;
		overflow: hidden;
		position: relative;
	}

	.domain-scroll-wrapper {
		display: flex;
		overflow-x: auto;
		scroll-behavior: smooth;
		-webkit-overflow-scrolling: touch;
		padding: 5px 0;
		scrollbar-width: none;
		/* Firefox */
		-ms-overflow-style: none;
		/* IE and Edge */
		white-space: nowrap;

		&::-webkit-scrollbar {
			display: none;
			/* Chrome, Safari, Opera */
		}
	}

	.domain-item {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 8px 16px;
		margin-right: 10px;
		border-radius: 20px;
		background: white;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		min-width: 90px;
		white-space: nowrap;
		transition: all 0.3s ease;

		&.active {
			background: #257CDB;
			color: white;

			.iconfont {
				color: white;
			}

			span {
				color: white;
			}
		}

		i {
			margin-right: 6px;
		}

		span {
			color: #257CDB;
		}
	}

	.scroll-indicator {
		display: flex;
		justify-content: center;
		margin-top: 8px;
	}

	.indicator-dot {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background: #ddd;
		margin: 0 4px;
		transition: background-color 0.3s;

		&.active {
			background: #257CDB;
		}
	}

	.search-bar {
		width: 100%;
		height: 53px;
		box-shadow: 0px 8px 3px 0px rgba(153, 153, 153, 0.08);
		border-radius: 12px;
		border: 1px solid #F1F1F1;

		.tape-box {
			width: 100%;
			height: 100%;

			img {
				height: 100%;
			}

			.show-chat-tip {
				font-size: 14px;
				color: #666060;
				/* 添加动画 */
				animation: bounce 1.5s ease-in-out infinite;
				/* 利用变量动态计算动画延迟时间 */
				animation-delay: calc(.05s * var(--i));
			}
		}
	}

	:deep(.el-input__wrapper) {
		box-shadow: none;
	}

	.icon-fasong,
	.a-3 {
		color: #2474ff;
	}

	.icon-fasong {
		font-size: 30px;
	}

	.a-3 {
		font-size: 28px;
	}
}

.domain-icon {
	width: 24px;
	height: 24px;
	margin-right: 4px;
	vertical-align: middle;
}
</style>
